package com.android.dx.youzan.meiye;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.dx.youzan.app.App;
import com.android.dx.youzan.app.Cookies;
import com.android.dx.youzan.meiye.model.CardGoods;
import com.lg.meng.utils.ThreadUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author: Ligang
 * Date: 2020/01/10
 * Description:
 */
public class CardMain {
    static OkHttpClient okHttpClient = new OkHttpClient();

    public static void main(String[] args) {
        ThreadUtils.runOnThread(() -> {
            Cookies cookies = App.getCookie();
            String cookie = cookies.getCookie();
            String _csrf = cookies.get_csrf();
            String kdtId = "43990976";
            String deptId = "43993058";
            listMemberCard(cookie, _csrf, kdtId, deptId);

        });
    }

    public static void listMemberCard(String cookie, String _csrf, String kdtId, String deptId) {
        String url = "https://mei1cxndddbnxeobh.youzan.com/api/h5/free/mei/card/buyer/listMemberCard?_csrf=" + _csrf;
        String bodyJson = "{\n" +
                "\t\"json\": \"{\\\"keyword\\\":\\\"\\\",\\\"desc\\\":1,\\\"pageNo\\\":1,\\\"pageSize\\\":20" +
                ",\\\"cardType\\\":0,\\\"kdtId\\\":\\\"" + kdtId + "\\\",\\\"deptId\\\":\\\"" + deptId + "\\\"}\"\n" +
                "}";

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .build();
        String string = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code") == 10000) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                log("查询到" + jsonArray.size() + "个卡商品");
                int goodsIndex = (int) (Math.random() * jsonArray.size());
                JSONObject itemObj = jsonArray.getJSONObject(goodsIndex);
                CardGoods goods = JSON.parseObject(itemObj.toJSONString(), CardGoods.class);
                log("开始购买第" + (goodsIndex + 1) + "个卡商品");
                orderBuyerSave(cookie, _csrf, kdtId, deptId, goods);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void orderBuyerSave(String cookie, String _csrf, String kdtId, String deptId, CardGoods cardGoods) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/order/buyer/save?_csrf=" + _csrf;
        String bodyJson = "{\n" +
                "\t\"json\": \"{\\\"orderItems\\\":[{\\\"itemSnapshotId\\\":" + cardGoods.getCardSnapshotId()
                + ",\\\"itemType\\\":4,\\\"itemId\\\":\\\"" + cardGoods.getPrepaidId() + "\\\",\\\"originPrice\\\":"
                + cardGoods.getCardPrice() + ",\\\"num\\\":1,\\\"realPay\\\":" + cardGoods.getCardPrice() + "}]" +
                ",\\\"type\\\":2,\\\"kdtId\\\":\\\"" + kdtId + "\\\",\\\"deptId\\\":\\\"" + deptId + "\\\"}\"\n" +
                "}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .build();
        String string = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                String orderNo = jsonObject.getJSONObject("data").getString("orderNo");
                log("orderBuyerSave成功:orderNo:" + orderNo);
                createAccountRecharge(cookie, _csrf, kdtId, deptId, cardGoods, orderNo);
            } else {
                log("orderBuyerSave失败：" + jsonObject.getString("message"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void createAccountRecharge(String cookie, String _csrf, String kdtId, String deptId, CardGoods cardGoods, String orderNo) {
        String url = "https://cashier.youzan.com/pay/mei/api/mei/recharge/buyer/create_account_recharge?_csrf=" + _csrf + "&json="
                + "{\"orderNo\":\"" + orderNo + "\",\"cardAlias\":\"" + cardGoods.getCardAlias()
                + "\",\"channelType\":4,\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                log("createAccountRecharge成功，开始获取支付链接");
                ServiceMain.拿支付链接(jsonObject);
            } else {
                log("createAccountRecharge失败：" + jsonObject.getString("message"));
                log("createAccountRecharge返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("createAccountRecharge失败：" + e.getMessage());
        }
    }

    private static void log(Object obj) {
        Log.e(TAG, obj + "");
        EventBus.getDefault().post(obj.toString());
    }

    private static final String TAG = "youzanmeiye";
}
